/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package JavaFiler;

import java.beans.Statement;
import java.util.ArrayList;
import java.util.Random;
import java.io.Serializable;
import java.sql.*;
import javax.enterprise.context.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author Per Stian Hoff & Gjerde
 */
@Named("tasks")
@SessionScoped
public class TaskBean implements Serializable, Constants {

    private String name;
    //private int currentTask = 0;
    private String currentRoom;
    private int chooseTaskType = 1;
    dbConnection dbCon = new dbConnection();
    private ArrayList<Task> tasks = new ArrayList<Task>();
    private boolean hasAlt = false;
    private Task storeTask;
    //private String image_URL;
    private int imageNumber;
    private int newNumber = 0;
    private boolean checkNumberAdded = false;
    private String alt1, alt2, alt3 = "";
    private ArrayList<String> Image_list;
    private Integer answer;
    private int points = 0;
    private int wrong = 0;
    private int gameID = 0;
    private ArrayList<Integer> taskID;
    private int counter = 0;
    private Task currentTask;
    private boolean haveActiveGame = false;
    private boolean doNotAdd = false;
    private int resultPoints;
    //private ArrayLis<Integer> h

    private void getUserData() {
        //Finner brukerdata
        ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
        Object requestObject = context.getRequest();
        if (!(requestObject instanceof HttpServletRequest)) {
            return;
        }
        HttpServletRequest request = (HttpServletRequest) requestObject;
        name = request.getRemoteUser();
    }

    public String getUsername() {
        //Finner brukernavn
        if (name == null) {
            getUserData();
        }
        return name == null ? "" : name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name){
        this.name = name;
    }
    public ArrayList<Task> getTableTasksAdmin() throws SQLException {
        //Finner oppgavene og legger det i ArrayList

        if (tasks == null) {
            tasks = new ArrayList<Task>();
        }

        if (chooseTaskType == 1) {
            this.currentRoom = PLUS;
        } else if (chooseTaskType == 2) {
            this.currentRoom = MINUS;
        } else if (chooseTaskType == 3) {
            this.currentRoom = MULTIPLY;
        } else if (chooseTaskType == 4) {
            this.currentRoom = DIVIDE;
        }

        getTasksRoom();
        return tasks;
    }

    public ArrayList<Task> getTableTasks() throws SQLException {
        //Finner oppgavene og legger det i ArrayList
        if (currentRoom == null) {
            currentRoom = PLUS;
        }
        if (tasks == null) {
            tasks = new ArrayList<Task>();
        }
        if (taskID == null) {
            taskID = new ArrayList();
        }

        getTasksRoom();
        int ok = getActiveRoom();
        if (ok == 0) {
            setNewActiveGame();
            getActiveRoom();
            setNewActiveGameTaskOrder();
            getActiveRoomOrder();
        } else {
            getActiveRoomOrder();
        }
        return tasks;
    }

    synchronized private void getTasksRoom() throws SQLException {
        //Finner oppgavene og legger det i en ArrayList.
        Connection connection = dbCon.getCon();
        tasks.clear();
        try {
            PreparedStatement prep = connection.prepareStatement("Select * from oppgave WHERE oppgavetype=?");
            prep.setString(1, currentRoom.toLowerCase().trim());
            ResultSet res = prep.executeQuery();
            try {

                while (res.next()) {
                    tasks.add(
                            new Task(
                            res.getInt("oppgave_id"),
                            res.getString("oppgavetype"),
                            res.getInt("vanskelighet"),
                            res.getString("tekst"),
                            res.getInt("svar"),
                            res.getString("bildenavn"),
                            res.getInt("ukjent"),
                            res.getInt("alt")));
                }
                res.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            //Henter hint
            PreparedStatement prep2 = connection.prepareStatement("Select * from hint WHERE oppgavetype=?");
            prep2.setString(1, currentRoom.toLowerCase().trim());
            ResultSet res2 = prep2.executeQuery();
            ArrayList<String> hint = new ArrayList();
            try {
                while (res2.next()) {
                    hint.add(res2.getString("bildenavn"));
                }
                addHint(hint);
                res2.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            //Henter tall
            PreparedStatement prep3 = connection.prepareStatement("Select * from tall");
            ResultSet res3 = prep3.executeQuery();
            ArrayList<TaskNumber> number = new ArrayList();
            try {
                while (res3.next()) {
                    number.add(new TaskNumber(
                            res3.getInt("oppgave_id"),
                            res3.getInt("verdi"),
                            res3.getInt("tall_id")));
                }
                addTaskNumbers(number);
                res3.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            //Henter alternativer
            PreparedStatement prep4 = connection.prepareStatement("Select * from alternativ");
            ResultSet res4 = prep4.executeQuery();
            ArrayList<TaskAlt> alt = new ArrayList();
            try {
                while (res4.next()) {
                    alt.add(new TaskAlt(
                            res4.getInt("oppgave_id"),
                            res4.getString("alt"),
                            res4.getInt("alt_id")));
                }
                addTaskAlt(alt);
                res4.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            dbCon.disconnect();
        }
    }

    synchronized private int getActiveRoom() throws SQLException {

        Connection connection = dbCon.getCon();
        points = 0;
        counter = 0;
        gameID = 0;
        try {
            //Finner score og neste spørsmål
            String username = getUsername();
            PreparedStatement prep = connection.prepareStatement("select * from aktivt_spill WHERE brukernavn = ? and spilltype = ?");
            prep.setString(1, username.toLowerCase().trim());
            prep.setString(2, currentRoom.toLowerCase().trim());
            ResultSet res = prep.executeQuery();
            try {
                while (res.next()) {
                    points = res.getInt("score");
                    counter = res.getInt("neste_spm");
                    gameID = res.getInt("spill_id");
                }
                res.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            dbCon.disconnect();
        }
        return gameID;
    }

    synchronized private void getActiveRoomOrder() throws SQLException {
        Connection connection = dbCon.getCon();
        taskID.clear();
        try {
            //Finne fra oppgaver i spill
            PreparedStatement prep2 = connection.prepareStatement("SELECT * FROM oppgaver_i_spill WHERE spill_ID = ?");
            prep2.setInt(1, gameID);

            ResultSet res2 = prep2.executeQuery();
            try {
                while (res2.next()) {
                    taskID.add(res2.getInt("oppgave_id"));
                }
                res2.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            dbCon.disconnect();
        }
    }

    public void setCurrentRoom(int roomNumber) throws SQLException {
        //Blir kalt når brukeren skal inn i et rom.
        currentTask = new Task();
        if (roomNumber == 1) {
            this.currentRoom = PLUS;
        } else if (roomNumber == 2) {
            this.currentRoom = MINUS;
        } else if (roomNumber == 3) {
            this.currentRoom = MULTIPLY;
        } else if (roomNumber == 4) {
            this.currentRoom = DIVIDE;
        }
        resultPoints = 0;
        points = 0;
        doNotAdd = false;
        getTableTasks();
        getCurrentTask();

    }

    synchronized private void setNewActiveGame() throws SQLException {
        //checkNumberAdded = false;
        PreparedStatement aktivtSpillTable = null;
        try {
            String username = getUsername();
            //Add
            aktivtSpillTable = dbCon.getCon().prepareStatement("INSERT INTO aktivt_spill(brukernavn, spilltype, neste_spm, score, antall_feil) values (?,?,?,?,?)");
            aktivtSpillTable.setString(1, username);
            aktivtSpillTable.setString(2, currentRoom.toLowerCase().trim());
            aktivtSpillTable.setInt(3, 1);
            aktivtSpillTable.setInt(4, 0);
            aktivtSpillTable.setInt(5, 0);
            aktivtSpillTable.executeUpdate();
            aktivtSpillTable.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            dbCon.disconnect();
        }
    }

    synchronized private void setNewActiveGameTaskOrder() throws SQLException {
        //checkNumberAdded = false;
        PreparedStatement oppgaverISpillTable = null;
        try {

            ArrayList<Integer> order = randomOrderOnTasks();
            for (int i = 0; i < order.size(); i++) {
                oppgaverISpillTable = dbCon.getCon().prepareStatement("INSERT INTO oppgaver_i_spill(spill_id, oppgave_id, neste_spm) values (?,?,?)");
                oppgaverISpillTable.setInt(1, gameID);
                oppgaverISpillTable.setInt(2, order.get(i));
                oppgaverISpillTable.setInt(3, i + 1);

                oppgaverISpillTable.executeUpdate();

            }
            oppgaverISpillTable.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            dbCon.disconnect();
        }
    }

    public ArrayList randomOrderOnTasks() {
        ArrayList<Integer> order = new ArrayList();
        Random rand = new Random();
        int totalTasksPerDif = (tasks.size() / 3);
        int number = rand.nextInt(totalTasksPerDif) + 1;
        order.add(number);
        boolean finnes = false;
        while (order.size() < totalTasksPerDif) {
            number = rand.nextInt(totalTasksPerDif) + 1;
            for (int j = 0; j < order.size(); j++) {
                if (number == order.get(j)) {
                    finnes = true;
                }
            }
            if (!finnes) {
                order.add(number);
            }
            finnes = false;
        }
        while (order.size() < totalTasksPerDif * 2) {
            number = rand.nextInt(totalTasksPerDif + totalTasksPerDif) + 1;
            for (int j = 0; j < order.size(); j++) {
                if (number == order.get(j)) {
                    finnes = true;
                }
            }
            if (!finnes) {
                order.add(number);
            }
            finnes = false;
        }
        while (order.size() < totalTasksPerDif * 3) {
            number = rand.nextInt(totalTasksPerDif + totalTasksPerDif + totalTasksPerDif) + 1;
            for (int j = 0; j < order.size(); j++) {
                if (number == order.get(j)) {
                    finnes = true;
                }
            }
            if (!finnes) {
                order.add(number);
            }
            finnes = false;
        }
        ArrayList<Integer> o = new ArrayList();
        if (currentRoom.toLowerCase().trim().equals(PLUS.toLowerCase().trim())) {
            o = order;
        } else if (currentRoom.toLowerCase().trim().equals(MINUS.toLowerCase().trim())) {
            for (int i = 0; i < order.size(); i++) {
                int tall = order.get(i);
                o.add(tall + (order.size() * 1));
            }
        } else if (currentRoom.toLowerCase().trim().equals(MULTIPLY.toLowerCase().trim())) {
            for (int i = 0; i < order.size(); i++) {
                int tall = order.get(i);
                o.add(tall + (order.size() * 2));
            }
        } else {
            for (int i = 0; i < order.size(); i++) {
                int tall = order.get(i);
                o.add(tall + (order.size() * 3));
            }
        }
        return o;
    }

    public int getCurrentTaskId() {
        return taskID.get(counter - 1);
    }

    public Task getCurrentTask() {
        currentTask = new Task();

        for (int i = 0; i < tasks.size(); i++) {
            if (tasks.get(i).getTaskId() == getCurrentTaskId()) {
                currentTask = tasks.get(i);
            }
        }
        setImageList();
        return currentTask;
    }

    public void setChooseTaskType(int chooseTaskType) {
        this.chooseTaskType = chooseTaskType;
    }

    public int getChooseTaskType() {
        return chooseTaskType;
    }

    public String getCurrentRoom() {
        //Finner hvilket rom brukeren er i.
        return currentRoom;
    }

    public int getNumberOfTasks() {
        //Finner antall oppgaver som er hentet ut fra databasen
        return tasks.size();
    }

    private void addHint(ArrayList<String> hint) {
        //Legger inn random hint i oppgavene.
        for (Task task : tasks) {
            task.setHint(hint.get(getRandomNumber(hint.size())));
        }
    }

    private void addTaskNumbers(ArrayList<TaskNumber> numbers) {
        for (int i = 0; i < tasks.size(); i++) {
            for (int j = 0; j < numbers.size(); j++) {
                if (tasks.get(i).getTaskId() == numbers.get(j).getTaskId()) {
                    tasks.get(i).setNumbers(numbers.get(j));
                }
            }
        }
    }

    private void addTaskAlt(ArrayList<TaskAlt> alt) {
        for (int i = 0; i < tasks.size(); i++) {
            for (int j = 0; j < alt.size(); j++) {
                if (tasks.get(i).getTaskId() == alt.get(j).getTaskId()) {
                    tasks.get(i).setAlt(alt.get(j));
                }
            }
        }
    }

    private int getRandomNumber(int i) {
        //Finner random tall fra 0 til i.
        Random gen = new Random();
        return gen.nextInt(i);
    }

    public void loadNextTask() {
        //Blir kalt hver gang en oppgave er svart og brukeren trykker på neste
        counter++;
        checkAnswer();
        answer = null;
        saveActiveGame();
        getCurrentTask();
    }

    public void saveActiveGame() {


        Connection connection = dbCon.getCon();

        try {
            //UPDATE ALT 1
            PreparedStatement prep = connection.prepareStatement("UPDATE aktivt_spill SET neste_spm = ?, score = ?, antall_feil = ? WHERE spill_id = ?");
            prep.setInt(1, counter);
            prep.setInt(2, points);
            prep.setInt(3, wrong);
            prep.setInt(4, gameID);
            int test1 = prep.executeUpdate();
            prep.close();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            dbCon.disconnect();
        }
    }

    public void checkAnswer() {
        //int currentTask = this.currentTask.getTaskId();
        if (currentTask.getIsUnknown() == false) {
            if (answer == currentTask.getAnswer()) {
                points += currentTask.getDifficulty();
            } else {
                points--;
                wrong++;
            }
        } else {
            ArrayList<TaskNumber> tall = currentTask.getNumbers();
            int svar = currentTask.getAnswer();
            if (currentTask.getTaskType().equals(PLUS.toLowerCase())) {
                for (int i = 0; i < tall.size(); i++) {
                    svar -= tall.get(i).getNumber();
                }
            } else if (currentTask.getTaskType().equals(MINUS.toLowerCase())) {
                if (tall.size() > 1) {
                    svar -= tall.get(0).getNumber();
                    for (int i = 1; i < tall.size(); i++) {
                        svar += tall.get(i).getNumber();
                    }
                } else {
                    svar = tall.get(0).getNumber() - svar;
                }
            }
            if (svar == answer) {
                points += currentTask.getDifficulty();
            } else {
                points--;
                wrong++;
            }
        }
    }

    public void setAnswer(Integer answer) {
        this.answer = answer;
    }

    public Integer getAnswer() {
        return answer;
    }

    public int getPoints() {
        return points;
    }

    public int getTaskNumber() {
        //Finner oppgave nummeret og legger til 1.
        return counter;
    }

    public boolean isHasAlt() {
        return hasAlt;
    }

    public void setHasAlt(boolean hasAlt) {
        this.hasAlt = hasAlt;
    }

    public Task getStoreTask() {
        return storeTask;
    }

    public void setStoreTask(Task storeTask) {
        this.storeTask = storeTask;
    }

    public int getImageNumber() {
        return imageNumber;
    }

    public void setImageNumber(int imageNumber) {
        this.imageNumber = imageNumber;
        if (imageNumber >= 0 && imageNumber < 7) {
            storeTask.setImg_name(IMG[imageNumber]);
        }
    }

    public boolean getIfOneUnknown() {
        return storeTask.getUnknown() == 1;
    }

    public void setNewNumber(int newNumber) {
        this.newNumber = newNumber;
    }

    public int getNewNumber() {
        return newNumber;
    }

    public void saveNewNumber() {
        checkNumberAdded = false;
        PreparedStatement tallTable = null;
        try {
            int tallAdded = -1;
            //Adds User
            tallTable = dbCon.getCon().prepareStatement("INSERT INTO tall(verdi, oppgave_id) values(?,?)");
            tallTable.setInt(1, newNumber);
            tallTable.setInt(2, storeTask.getTaskId());
            tallAdded = tallTable.executeUpdate();
            tallTable.close();

            if (tallAdded == 1) {
                this.checkNumberAdded = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            dbCon.disconnect();
        }
        getTallFromDB();
    }

    private void getTallFromDB() {
        Connection connection = dbCon.getCon();
        try {
            //Henter tall
            PreparedStatement prep3 = connection.prepareStatement("Select * from tall WHERE oppgave_id=?");
            prep3.setInt(1, storeTask.getTaskId());
            ResultSet res3 = prep3.executeQuery();
            ArrayList<TaskNumber> number = new ArrayList();
            try {
                while (res3.next()) {
                    number.add(new TaskNumber(
                            res3.getInt("oppgave_id"),
                            res3.getInt("verdi"),
                            res3.getInt("tall_id")));
                }
                addStoreTaskNumbers(number);
                res3.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            dbCon.disconnect();
        }
    }

    private void addStoreTaskNumbers(ArrayList<TaskNumber> numbers) {
        storeTask.clearNumbers();
        for (int j = 0; j < numbers.size(); j++) {
            storeTask.setNumbers(numbers.get(j));
        }
        newNumber = 0;
    }

    public void deleteNumber(TaskNumber t) {
        int deleteNumber = -1;
        try {
            PreparedStatement deleteStatementNumber = dbCon.getCon().prepareStatement("DELETE FROM tall WHERE tall_id=?");
            deleteStatementNumber.setInt(1, t.getNumberId());
            deleteNumber = deleteStatementNumber.executeUpdate();
            deleteStatementNumber.close();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            dbCon.disconnect();
        }
        getTallFromDB();
    }

    public void setNewAlts(String alt, int id) {
        storeTask.addNewAlt(alt, id);
    }

    public void setAlt1(String alt) {
        if (alt == null || alt.equals("")) {
            alt = "";
        }
        this.alt1 = alt;
        setNewAlts(alt1, 0);
    }

    public String getAlt1() {
        return storeTask.getAlt().get(0).getAlternative();
    }

    public void setAlt2(String alt) {
        if (alt == null || alt.equals("")) {
            alt = "";
        }
        this.alt2 = alt;
        setNewAlts(alt2, 1);
    }

    public String getAlt2() {
        return storeTask.getAlt().get(1).getAlternative();
    }

    public void setAlt3(String alt) {
        if (alt == null || alt.equals("")) {
            alt = "";
        }
        this.alt3 = alt;
        setNewAlts(alt3, 2);
    }

    public String getAlt3() {
        return storeTask.getAlt().get(2).getAlternative();
    }

    public void changeTask() {
        int ukjent;
        int alt;
        if (storeTask.getIsUnknown()) {
            ukjent = 1;
        } else {
            ukjent = 0;
        }
        if (storeTask.isDoHaveAlt()) {
            alt = 1;
        } else {
            alt = 0;
        }
        Connection connection = dbCon.getCon();

        try {
            //UPDATE ALT 1
            PreparedStatement prep = connection.prepareStatement("UPDATE alternativ SET alt = ? WHERE alt_id = ?");
            prep.setString(1, storeTask.getAlt().get(0).getAlternative());
            prep.setInt(2, storeTask.getAlt().get(0).getAltId());
            int test1 = prep.executeUpdate();
            prep.close();
            //UPDATE ALT 2
            PreparedStatement prep2 = connection.prepareStatement("UPDATE alternativ SET alt = ? WHERE alt_id = ?");
            prep2.setString(1, storeTask.getAlt().get(1).getAlternative());
            prep2.setInt(2, storeTask.getAlt().get(1).getAltId());
            int test2 = prep2.executeUpdate();
            prep2.close();
            //UPDATE ALT 3
            PreparedStatement prep3 = connection.prepareStatement("UPDATE alternativ SET alt = ? WHERE alt_id = ?");
            prep3.setString(1, storeTask.getAlt().get(2).getAlternative());
            prep3.setInt(2, storeTask.getAlt().get(2).getAltId());
            int test3 = prep3.executeUpdate();
            prep3.close();
            //UPDATE OPPGAVE
            PreparedStatement prep4 = connection.prepareStatement("UPDATE oppgave SET tekst = ?,svar = ?, bildenavn = ? , ukjent = ?, alt = ? WHERE oppgave_id = ?");
            prep4.setString(1, storeTask.getText());
            prep4.setInt(2, storeTask.getAnswer());
            prep4.setString(3, storeTask.getImg_name());
            prep4.setInt(4, ukjent);
            prep4.setInt(5, alt);
            prep4.setInt(6, storeTask.getTaskId());
            int test4 = prep4.executeUpdate();
            prep4.close();
            if (test1 == 1 && test2 == 1 && test3 == 1 && test4 == 1) {
                System.out.println("OPPDATERT OK !!!");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            dbCon.disconnect();
        }
    }

    public ArrayList getImageList() {
        return Image_list;
    }

    public ArrayList setImageList() {
        Image_list = new ArrayList();

        if (currentTask.getTaskType().toLowerCase().trim().equals(PLUS.toLowerCase().trim())) {
            Image_list = setImageListPlus();
        } else if (currentTask.getTaskType().toLowerCase().trim().equals(MINUS.toLowerCase().trim())) {
            Image_list = setImageListMinus();
        } else if (currentTask.getTaskType().toLowerCase().trim().equals(MULTIPLY.toLowerCase().trim())) {
            Image_list = setImageListPlus();
        }else{
            Image_list = setImageListPlus();
        }

        return Image_list;
    }

    public ArrayList setImageListMinus() {
        Image_list = new ArrayList();


        ArrayList<TaskNumber> numbers = new ArrayList();
        numbers = currentTask.getNumbers();
        if (numbers.size() == 1 && currentTask.getIsUnknown()==false) {
            if (currentTask.getImg_name().equals("terning")) {
                Image_list.add(URL + currentTask.getImg_name() + IMG_TYPE);
            } else {
                for (int j = 0; j < numbers.get(0).getNumber(); j++) {
                    Image_list.add(URL + currentTask.getImg_name() + IMG_TYPE);
                }
            }
        } else {
            for (int i = 0; i < numbers.size(); i++) {
                if (!currentTask.getImg_name().equals("terning")) {
                    for (int j = 0; j < numbers.get(i).getNumber(); j++) {
                        Image_list.add(URL + currentTask.getImg_name() + IMG_TYPE);
                    }
                    if (currentTask.getIsUnknown() && i == numbers.size() - 1) {
                        Image_list.add(URL + "minus" + IMG_TYPE);
                        Image_list.add(URL + "ukjent" + IMG_TYPE);
                        Image_list.add(URL + "lik" + IMG_TYPE);
                        for (int j = 0; j < currentTask.getAnswer(); j++) {
                            Image_list.add(URL + currentTask.getImg_name() + IMG_TYPE);
                        }
                    } else if (!currentTask.getIsUnknown() && i == numbers.size() - 1) {
                        Image_list.add(URL + "lik" + IMG_TYPE);
                        Image_list.add(URL + "sporsmalstegn" + IMG_TYPE);
                    } else {
                        Image_list.add(URL + "minus" + IMG_TYPE);
                    }
                } else {
                    Image_list.add(URL + currentTask.getImg_name() + numbers.get(i).getNumber() + IMG_TYPE);

                    if (currentTask.getIsUnknown() && i == numbers.size() - 1) {
                        Image_list.add(URL + "minus" + IMG_TYPE);
                        Image_list.add(URL + "ukjent" + IMG_TYPE);
                        Image_list.add(URL + "lik" + IMG_TYPE);
                    } else if (!currentTask.getIsUnknown() && i == numbers.size() - 1) {
                        Image_list.add(URL + "lik" + IMG_TYPE);
                        Image_list.add(URL + "sporsmalstegn" + IMG_TYPE);
                    } else {
                        Image_list.add(URL + "minus" + IMG_TYPE);
                    }
                }
            }
        }

        return Image_list;
        //if()
    }

    public ArrayList setImageListPlus() {
        Image_list = new ArrayList();

        ArrayList<TaskNumber> numbers = new ArrayList();
        numbers = currentTask.getNumbers();
        if (numbers.size() == 1 && currentTask.getIsUnknown()==false) {
            if (currentTask.getImg_name().equals("terning")) {
                Image_list.add(URL + currentTask.getImg_name() + IMG_TYPE);
            } else {
                for (int j = 0; j < numbers.get(0).getNumber(); j++) {
                    Image_list.add(URL + currentTask.getImg_name() + IMG_TYPE);
                }
            }
        } else {
        for (int i = 0; i < numbers.size(); i++) {
            if (!currentTask.getImg_name().equals("terning")) {
                for (int j = 0; j < numbers.get(i).getNumber(); j++) {
                    Image_list.add(URL + currentTask.getImg_name() + IMG_TYPE);
                }
                if (currentTask.getIsUnknown() && i == numbers.size() - 1) {
                    Image_list.add(URL + "pluss" + IMG_TYPE);
                    Image_list.add(URL + "ukjent" + IMG_TYPE);
                    Image_list.add(URL + "lik" + IMG_TYPE);
                    for (int j = 0; j < currentTask.getAnswer(); j++) {
                        Image_list.add(URL + currentTask.getImg_name() + IMG_TYPE);
                    }
                } else if (!currentTask.getIsUnknown() && i == numbers.size() - 1) {
                    Image_list.add(URL + "lik" + IMG_TYPE);
                    Image_list.add(URL + "sporsmalstegn" + IMG_TYPE);
                } else {
                    Image_list.add(URL + "pluss" + IMG_TYPE);
                }
            } else {
                Image_list.add(URL + currentTask.getImg_name() + numbers.get(i).getNumber() + IMG_TYPE);

                if (currentTask.getIsUnknown() && i == numbers.size() - 1) {
                    Image_list.add(URL + "pluss" + IMG_TYPE);
                    Image_list.add(URL + "ukjent" + IMG_TYPE);
                    Image_list.add(URL + "lik" + IMG_TYPE);
                } else if (!currentTask.getIsUnknown() && i == numbers.size() - 1) {
                    Image_list.add(URL + "lik" + IMG_TYPE);
                    Image_list.add(URL + "sporsmalstegn" + IMG_TYPE);
                } else {
                    Image_list.add(URL + "pluss" + IMG_TYPE);
                }
            }
        }
        }
        return Image_list;
        //if()
    }

    public boolean isImageOrNot() {
        boolean isImage = false;

        if (!currentTask.getImg_name().equals("null")) {
            isImage = true;
        }
        return isImage;
    }

    public String getAlt1CurrentTask() {
        Task t = getCurrentTask();
        return t.getAlt().get(0).getAlternative();
    }

    public String getAlt2CurrentTask() {
        Task t = getCurrentTask();
        return t.getAlt().get(1).getAlternative();
    }

    public String getAlt3CurrentTask() {
        Task t = getCurrentTask();
        return t.getAlt().get(2).getAlternative();
    }

    public boolean getIfLastQuestions() {
        boolean last = false;
        if (getNumberOfTasks() == getTaskNumber()) {
            last = true;
        }
        return last;
    }

    public void finishGame() throws SQLException {
        ArrayList<Integer> stats = getTries();
        int triesDB = stats.get(0);
        int scoreDB = stats.get(1);
        checkAnswer();
        addGameStats(triesDB, scoreDB);
        deleteFromActiveGame();

    }

    public void deleteFromActiveGame() throws SQLException {
        int deleteActiveGameOk = -1;
        int deleteTaskInGameOk = -1;

        try {
            PreparedStatement deleteActiveGame = dbCon.getCon().prepareStatement("DELETE FROM aktivt_spill WHERE spill_id = ?");
            deleteActiveGame.setInt(1, gameID);
            deleteActiveGameOk = deleteActiveGame.executeUpdate();
            deleteActiveGame.close();

            PreparedStatement deleteTaskInGame = dbCon.getCon().prepareStatement("DELETE FROM oppgaver_i_spill WHERE spill_id = ?");
            deleteTaskInGame.setInt(1, gameID);
            deleteTaskInGameOk = deleteTaskInGame.executeUpdate();
            deleteTaskInGame.close();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            dbCon.disconnect();
        }
    }

    public void addGameStats(int triesDB, int scoreDB) {

        Connection connection = dbCon.getCon();
        if (scoreDB < points) {
            scoreDB = points;
        }
        if (doNotAdd == false) {
            resultPoints = points;
            try {
                //UPDATE ALT 1
                String sql = "UPDATE spillarkiv SET forsok_pluss = ?, pluss_score = ?, forsok_minus = ?, minus_score = ?,"
                        + "forsok_gange = ?, gange_score = ?,forsok_deling = ?, deling_score = ? WHERE brukernavn = ?";
                PreparedStatement prep = connection.prepareStatement(sql);
                if (currentRoom.toLowerCase().trim().equals(PLUS.toLowerCase().trim())) {
                    prep.setInt(1, triesDB + 1);
                    prep.setInt(2, scoreDB);
                    prep.setInt(3, 0);
                    prep.setInt(4, 0);
                    prep.setInt(5, 0);
                    prep.setInt(6, 0);
                    prep.setInt(7, 0);
                    prep.setInt(8, 0);
                    prep.setString(9, getUsername());
                } else if (currentRoom.toLowerCase().trim().equals(MINUS.toLowerCase().trim())) {
                    prep.setInt(1, 0);
                    prep.setInt(2, 0);
                    prep.setInt(3, triesDB + 1);
                    prep.setInt(4, scoreDB);
                    prep.setInt(5, 0);
                    prep.setInt(6, 0);
                    prep.setInt(7, 0);
                    prep.setInt(8, 0);
                    prep.setString(9, getUsername());
                } else if (currentRoom.toLowerCase().trim().equals(MULTIPLY.toLowerCase().trim())) {
                    prep.setInt(1, 0);
                    prep.setInt(2, 0);
                    prep.setInt(3, 0);
                    prep.setInt(4, 0);
                    prep.setInt(5, triesDB + 1);
                    prep.setInt(6, scoreDB);
                    prep.setInt(7, 0);
                    prep.setInt(8, 0);
                    prep.setString(9, getUsername());
                } else {
                    prep.setInt(1, 0);
                    prep.setInt(2, 0);
                    prep.setInt(3, 0);
                    prep.setInt(4, 0);
                    prep.setInt(5, 0);
                    prep.setInt(6, 0);
                    prep.setInt(7, triesDB + 1);
                    prep.setInt(8, scoreDB);
                    prep.setString(9, getUsername());
                }

                int test1 = prep.executeUpdate();
                prep.close();

            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                dbCon.disconnect();
            }
        }
    }

    private ArrayList<Integer> getTries() {
        Connection connection = dbCon.getCon();
        ArrayList<Integer> stats = new ArrayList();
        String username = getUsername();
        try {
            PreparedStatement prep3 = connection.prepareStatement("Select * from spillarkiv WHERE brukernavn=?");
            prep3.setString(1, username);
            ResultSet res3 = prep3.executeQuery();

            try {
                while (res3.next()) {
                    if (currentRoom.toLowerCase().trim().equals(PLUS.toLowerCase().trim())) {
                        stats.add(res3.getInt("forsok_pluss"));
                        stats.add(res3.getInt("pluss_score"));
                    } else if (currentRoom.toLowerCase().trim().equals(MINUS.toLowerCase().trim())) {
                        stats.add(res3.getInt("forsok_minus"));
                        stats.add(res3.getInt("minus_score"));
                    } else if (currentRoom.toLowerCase().trim().equals(MULTIPLY.toLowerCase().trim())) {
                        stats.add(res3.getInt("forsok_gange"));
                        stats.add(res3.getInt("gange_score"));
                    } else {
                        stats.add(res3.getInt("forsok_deling"));
                        stats.add(res3.getInt("deling_score"));
                    }

                }
                res3.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            dbCon.disconnect();
        }
        return stats;
    }

    public String getImageHint() {
        return URL_HINT + currentTask.getHint().toLowerCase().trim() + IMG_TYPE;
    }

    public int getResultPoints() {
        doNotAdd = true;
        return resultPoints;
    }

    public String getResultImageUrl() {
        String url = "";
        if (resultPoints > 15) {
            url = URL_IMAGES + "kalle_superman_450px_trans" + IMG_TYPE;
        } else if (getIfUnlocked()) {
            url = URL_IMAGES + "kalle_muscleman_450px_trans" + IMG_TYPE;
        } else {
            url = URL_IMAGES + "kalle_stop_450px_trans" + IMG_TYPE;
        }
        return url;
    }

    public boolean getIfUnlocked() {
        boolean ok = false;
        if (resultPoints > 8) {
            ok = true;
        }
        return ok;
    }
}
